import koaRequest from 'koa2-request';
const env = process.env;

const httpRequest = async (method, url, options = {}, ctx) => {
  const larkData = ctx.session.larkAuth;
  const larkAuthEncrypt = (str) => {
    return Buffer.from(str).toString('base64');
  };
  const defaultHeaders = {
    'Content-Type': 'application/json',
    Authorization: larkData?.access_token
      ? `Bearer ${larkData?.access_token}`
      : `Basic ${larkAuthEncrypt(`${env.LARK_APP_ID}:${env.LARK_APP_SECRET}`)}`
  };
  const { headers = {}, body = {}, qs = {}, timeout = 5000 } = options;
  try {
    const response = await koaRequest({
      method,
      url: `${env.LARK_API_HEAD}${url}`,
      headers: { ...defaultHeaders, ...headers },
      json: true, // 自动解析 JSON 响应
      body: method !== 'GET' ? body : undefined, // GET 请求不需要 body
      qs: method === 'GET' ? qs : undefined // GET 请求使用 qs
    });
    // console.log(response, 121231)
    // 返回响应数据和状态码
    return {
      status: response.statusCode,
      data: response.body
    };
  } catch (error) {
    // 捕获错误并抛出
    throw new Error(`HTTP request failed: ${error.message}`);
  }
};

function httpMiddleware() {
  return async (ctx, next) => {
    // 挂载到 ctx
    ctx.larkHttp = {
      get: (url, options) => httpRequest('GET', url, options, ctx),
      post: (url, options) => httpRequest('POST', url, options, ctx)
    };

    // 继续执行后续中间件
    await next();
  };
}

export default httpMiddleware;
